<script setup lang="ts">
import { computed, ref } from 'vue'
import HmList from './components/HmList.vue.js'

const list = ref<
  {
    id: number
    name: string
    price: number
    num: number
  }[]
>([
  { id: 1, name: '西瓜', price: 4, num: 3 },
  { id: 2, name: '苹果', price: 6, num: 6 },
  { id: 3, name: '雪梨', price: 5, num: 3 }
])
const total = computed<number>(() => {
  return list.value.reduce((prev, item) => {
    return prev + item.price * item.num
  }, 0)
})

// 修改某个商品的数据
const setNum = (id: number, step: number) => {
  const findItem = list.value.find(item => item.id === id)
  if (findItem) {
    findItem.num += step
  }
}
</script>

<template>
  <div class="main">
    <div class="item">
      <div class="name">商品名</div>
      <div class="price">单价</div>
      <div class="count">数量</div>
    </div>
    <HmList :list="list" @setNum="setNum"></HmList>
    <div class="total">总价: {{ total }}元</div>
  </div>
</template>

<style>
.item {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-evenly;
}
.total {
  text-align: right;
}
</style>
